package com.spica.platform.oauth.server.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spica.platform.base.exception.instance.BizException;
import com.spica.platform.base.model.Client;
import com.spica.platform.base.model.PageResult;
import com.spica.platform.base.model.ResponseEntity;
import com.spica.platform.uaa.client.model.ClientQueryParam;
import com.spica.platform.uaa.client.service.IClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 应用相关接口
 */
@Slf4j
@Api(tags = "应用")
@RestController
@RequestMapping("/clients")
public class ClientController {
	@Autowired
	private IClientService clientService;

	@GetMapping("/list")
	@ApiOperation(value = "根据参数查询所有应用列表")
	public PageResult<Client> list(Page<Client> page, ClientQueryParam clientQueryParam) {
		return clientService.listClient(page, clientQueryParam);
	}

	@GetMapping("/{id}")
	@ApiOperation(value = "根据id获取应用")
	public ResponseEntity<Client> getClientById(@PathVariable Long id) {
		return ResponseEntity.succeed(clientService.getById(id));
	}
	
	
	@GetMapping("/client")
	@ApiOperation(value = "根据clientId获取应用")
	public Client getByClientId(@RequestParam String clientId) {
		return clientService.loadClientByClientId(clientId) ;
	}

	@GetMapping("/all")
	@ApiOperation(value = "查询所有应用")
	public ResponseEntity<List<Client>> allClient() {
		Page<Client> page = new Page<>(1, -1);
		PageResult<Client> resultPage = clientService.listClient(page, new ClientQueryParam());
		return ResponseEntity.succeed(resultPage.getData());
	}

	@PostMapping("/{id}")
	@ApiOperation(value = "删除应用")
	public ResponseEntity removeClientById(@PathVariable Long id) {

		Try.of(() -> clientService.delClient(id)).onFailure(ex -> log.error("client-delete-error", ex))
				.getOrElseThrow(item -> new BizException("操作失败"));
		return ResponseEntity.succeed("操作成功");

	}

	@PostMapping("/saveOrUpdate")
	@ApiOperation(value = "保存或者修改应用")
	public ResponseEntity saveOrUpdate(@RequestBody Client client) throws Exception {

		Try.of(() -> clientService.saveClient(client)).onFailure(ex -> log.error("client-saveOrUpdate-error", ex))
				.getOrElseThrow(item -> new BizException("操作失败"));
		return ResponseEntity.succeed("操作成功");

	}
}
